# 编译类
import os
from PyPDF2 import PdfReader
import glob

class Compile:
    def __init__(self, tex_content, engine = "pdflatex"):
        self.tex_content = tex_content
        self.engine = engine


    def run(self):
        with open("temp_latex.tex", "w", encoding="utf-8") as f:
            f.write(self.tex_content)
        returncode = os.system(f"{self.engine} --interaction=nonstopmode temp_latex.tex")

        os.system("pdftocairo -r 300 -png temp_latex.pdf")

        result = []
        if returncode == 0:
            reader = PdfReader("temp_latex.pdf")
            num_pages = len(reader.pages)
            for page in range(1, num_pages + 1):
                with open(f"temp_latex-{page}.png", "rb") as f:   
                    result.append(f.read())
        else:
            with open("./data/error.jpg", "rb") as f:   
                result.append(f.read())

        self.clear()
        return result
    

    def clear(self):
        current_dir = os.getcwd()

        files_to_delete = glob.glob(os.path.join(current_dir, "temp_latex*"))

        # 删除匹配的文件
        for file_path in files_to_delete:
            try:
                os.remove(file_path)
            except Exception as e:
                print(f"Error deleting {file_path}: {e}")